import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// import 'package:provider/provider.dart';

// import 'MarketItemWidget.dart';
// import 'MarketProvider.dart';

import 'dart:convert';
// import 'package:web_socket_channel/web_socket_channel.dart';
// import 'package:web_socket_channel/status.dart' as status;

import 'FakeWebSocketServer.dart';
import 'MarketProvider.dart';

class MarketScreen extends StatefulWidget {
  const MarketScreen({super.key});

  @override
  _MarketScreenState createState() => _MarketScreenState();
}

class _MarketScreenState extends State<MarketScreen> {
  late FakeWebSocketServer fakeServer;

  @override
  void initState() {
    super.initState();
    fakeServer = FakeWebSocketServer();

    // 监听 WebSocket 更新
    fakeServer.stream.listen((data) {
      print("📡 服务器推送数据: $data");

      final decodedData = jsonDecode(data);
      if (decodedData is Map &&
          decodedData.containsKey("code") &&
          decodedData.containsKey("price")) {
        String code = decodedData["code"];
        double newPrice = decodedData["price"];
        Provider.of<MarketProvider>(context, listen: false)
            .updateMarketItem(code, newPrice);
      }
    });

    //汇率模拟服务器数据
    // var server = FakeWebSocketServer();
    // server.stream.listen((data) {
    //   print("📡 服务器推送数据: $data");
    // });
  }

  @override
  void dispose() {
    fakeServer.dispose();
    print("${widget.runtimeType} 被卸载！");

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("市场行情")),
      body: Consumer<MarketProvider>(
        builder: (context, provider, child) {
          return ListView.builder(
            itemCount: provider.items.length,
            itemBuilder: (context, index) {
              final item = provider.items[index];
              return ListTile(
                title: Text("${item.name} (${item.code})"),
                subtitle: Text("当前价格: ${item.currentPrice.toStringAsFixed(2)}"),
                trailing: Text(
                  item.change.toStringAsFixed(2),
                  style: TextStyle(
                    color: item.change >= 0 ? Colors.green : Colors.red,
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }
}


/*
class MarketScreen extends StatefulWidget {
  const MarketScreen({super.key});

  @override
  _MarketScreenState createState() => _MarketScreenState();
}

class _MarketScreenState extends State<MarketScreen> {
  final ValueNotifier<List<dynamic>> marketDataNotifier = ValueNotifier([]);

  @override
  void initState() {
    super.initState();
    _listenToServer();
  }

  void _listenToServer() {
    fakeServer.stream.listen((data) {
      final decodedData = jsonDecode(data);
      marketDataNotifier.value = decodedData; // 只更新数据，避免整个页面重建
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("实时行情")),
      body: ValueListenableBuilder<List<dynamic>>(
        valueListenable: marketDataNotifier,
        builder: (context, marketData, child) {
          return marketData.isNotEmpty
              ? ListView.builder(
                  itemCount: marketData.length,
                  itemBuilder: (context, index) {
                    return MarketItemWidget(marketData[index]);
                  },
                )
              : Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

// 只负责显示一条数据的组件
class MarketItemWidget extends StatelessWidget {
  final Map<String, dynamic> data;

  MarketItemWidget(this.data);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(data["name"], style: TextStyle(fontSize: 18)),
      trailing: Text("\$${data["price"]}",
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
    );
  }
}

*/

// class MarketScreen extends StatefulWidget {
//   const MarketScreen({super.key});

//   @override
//   _MarketScreenState createState() => _MarketScreenState();
// }

// class _MarketScreenState extends State<MarketScreen> {
//   late WebSocketChannel channel;
//   List<dynamic> marketData = [];
//   bool isConnected = false;

//   @override
//   void initState() {
//     super.initState();
//     connectWebSocket();
//   }

//   void connectWebSocket() {
//     channel = WebSocketChannel.connect(Uri.parse('ws://localhost:8080'));

//     channel.stream.listen(
//       (data) {
//         final decodedData = jsonDecode(data);
//         setState(() {
//           marketData = decodedData["market"];
//           isConnected = true;
//         });
//       },
//       onError: (error) {
//         print("❌ WebSocket 错误: $error");
//         reconnect();
//       },
//       onDone: () {
//         print("⚠️ WebSocket 断开，尝试重连...");
//         reconnect();
//       },
//     );
//   }

//   void reconnect() {
//     setState(() => isConnected = false);
//     Future.delayed(Duration(seconds: 5), () {
//       if (!isConnected) {
//         connectWebSocket();
//       }
//     });
//   }

//   @override
//   void dispose() {
//     channel.sink.close(status.goingAway);
//     super.dispose();
//   }

//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(title: Text("实时行情")),
//       body: isConnected
//           ? ListView.builder(
//               itemCount: marketData.length,
//               itemBuilder: (context, index) {
//                 final item = marketData[index];
//                 return ListTile(
//                   title: Text(item["name"], style: TextStyle(fontSize: 18)),
//                   trailing: Text("\$${item["price"]}",
//                       style:
//                           TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
//                 );
//               },
//             )
//           : Center(child: CircularProgressIndicator()),
//     );
//   }
// }



// class MarketScreen extends StatelessWidget {
//   const MarketScreen({super.key});

//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(title: Text("指数行情")),
//       body: Consumer<MarketProvider>(
//         builder: (context, provider, child) {
//           final marketData = provider.marketData;
//           return ListView.builder(
//             itemCount: marketData.length,
//             itemBuilder: (context, index) {
//               final key = marketData.keys.elementAt(index);
//               final value = marketData[key];
//               return ListTile(
//                 title: Text("$key"),
//                 subtitle: Text("价格: $value"),
//               );
//             },
//           );
//         },
//       ),
//     );
//   }
// }


// class MarketScreen extends StatelessWidget {
//   const MarketScreen({super.key});

//   @override
//   Widget build(BuildContext context) {
//     final marketProvider = Provider.of<MarketProvider>(context);

//     return Scaffold(
//       appBar: AppBar(title: const Text("市场行情")),
//       body: ListView.builder(
//         itemCount: marketProvider.items.length,
//         itemBuilder: (context, index) {
//           return MarketItemWidget(item: marketProvider.items[index]);
//         },
//       ),
//     );
//   }
// }
